package com.zjx.activiti.controller;

import com.zjx.activiti.service.HistoryInfoService;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;

/**
 * 历史管理
 *
 * @Auther: zhaojx
 * @Date: 2021/8/25 11:43
 */
@RestController
@RequestMapping("history")
public class HistoryController {

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    ProcessEngineConfiguration processEngineConfiguration;
    @Autowired
    ProcessEngineFactoryBean processEngine;

    @Autowired
    TaskService taskService;

    /**
     * 我的审批记录
     *
     * @param userId
     * @return
     */
    @GetMapping(value = "/tasks/myc")
    public Object myTasksCompleted(@RequestParam("userId") String userId) {
        List<HistoricTaskInstance> instances = historyService.createHistoricTaskInstanceQuery().
                finished().taskAssignee(userId).orderByTaskCreateTime().desc().list();
        return instances;
    }

    /**
     * 我发起的记录
     *
     * @param userId
     * @return
     */
    @GetMapping(value = "/process/mys")
    public Object myProcessStarted(@RequestParam("userId") String userId) {
        return historyService.createHistoricProcessInstanceQuery().startedBy(userId).list();
    }

    /**
     * 读取带跟踪的图片
     */
    @RequestMapping("/view")
    public void test(HttpServletResponse response, @RequestParam("processInstanceId") String processInstanceId) throws Exception {
        //获取历史流程实例
        HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        processEngineConfiguration = processEngine.getProcessEngineConfiguration();
        Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);

        ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
        ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(processInstance.getProcessDefinitionId());

        List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
        //高亮环节id集合
        List<String> highLightedActivitis = new ArrayList<String>();
        //高亮线路id集合
        List<String> highLightedFlows = getHighLightedFlows(definitionEntity, highLightedActivitList);

        //当前流程实例执行到哪个节点
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createExecutionQuery().executionId(processInstanceId).singleResult();// 执行实例
        highLightedActivitis.add(execution.getActivityId());

        //输出
        InputStream imageStream = diagramGenerator.generateDiagram(bpmnModel, "png", highLightedActivitis, highLightedFlows, "宋体", "宋体", "宋体", null, 1.0);
        response.setContentType("image/jpeg");
        // 输出资源内容到相应对象
        byte[] b = new byte[1024];
        int len;
        while ((len = imageStream.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }

    }

    /**
     * 获取需要高亮的线
     *
     * @param processDefinitionEntity
     * @param historicActivityInstances
     * @return
     */
    private List<String> getHighLightedFlows(
            ProcessDefinitionEntity processDefinitionEntity,
            List<HistoricActivityInstance> historicActivityInstances) {
        List<String> highFlows = new ArrayList<String>();// 用以保存高亮的线flowId
        for (int i = 0; i < historicActivityInstances.size() - 1; i++) {// 对历史流程节点进行遍历
            ActivityImpl activityImpl = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i)
                            .getActivityId());// 得到节点定义的详细信息
            List<ActivityImpl> sameStartTimeNodes = new ArrayList<ActivityImpl>();// 用以保存后需开始时间相同的节点
            ActivityImpl sameActivityImpl1 = processDefinitionEntity
                    .findActivity(historicActivityInstances.get(i + 1)
                            .getActivityId());
            // 将后面第一个节点放在时间相同节点的集合里
            sameStartTimeNodes.add(sameActivityImpl1);
            for (int j = i + 1; j < historicActivityInstances.size() - 1; j++) {
                HistoricActivityInstance activityImpl1 = historicActivityInstances
                        .get(j);// 后续第一个节点
                HistoricActivityInstance activityImpl2 = historicActivityInstances
                        .get(j + 1);// 后续第二个节点
                if (activityImpl1.getStartTime().equals(
                        activityImpl2.getStartTime())) {
                    // 如果第一个节点和第二个节点开始时间相同保存
                    ActivityImpl sameActivityImpl2 = processDefinitionEntity
                            .findActivity(activityImpl2.getActivityId());
                    sameStartTimeNodes.add(sameActivityImpl2);
                } else {
                    // 有不相同跳出循环
                    break;
                }
            }
            List<PvmTransition> pvmTransitions = activityImpl
                    .getOutgoingTransitions();// 取出节点的所有出去的线
            for (PvmTransition pvmTransition : pvmTransitions) {
                // 对所有的线进行遍历
                ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition
                        .getDestination();
                // 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
                if (sameStartTimeNodes.contains(pvmActivityImpl)) {
                    highFlows.add(pvmTransition.getId());
                }
            }
        }
        return highFlows;
    }



//    /**  @Autowired
//     * 查询流程 （高亮显示已办和我的待办流程）
//     * @param instanceId
//     * @return
//     */
//    @RequestMapping("/getApply_status")
//    public Map<String,Object> getApplyStatus(@RequestParam String instanceId){
//
//        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
//                .processInstanceId(instanceId).singleResult();
//        //获取bpmnModel对象
//        BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
//        //因为我们这里只定义了一个Process 所以获取集合中的第一个即可
//        Process process = bpmnModel.getProcesses().get(0);
//        //获取所有的FlowElement信息
//        Collection<FlowElement> flowElements = process.getFlowElements();
//
//        Map<String,String> map = new HashMap<>();
//        for (FlowElement flowElement : flowElements) {
//            //判断是否是连线
//            if (flowElement instanceof SequenceFlow) {
//                SequenceFlow sequenceFlow = (SequenceFlow) flowElement;
//                String ref = sequenceFlow.getSourceRef();
//                String targetRef = sequenceFlow.getTargetRef();
//                map.put(ref+targetRef,sequenceFlow.getId());
//            }
//        }
//
//        //获取流程实例 历史节点(全部)
//        List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery()
//                .processInstanceId(instanceId)
//                .list();
//        //各个历史节点   两两组合 key
//        Set<String> keyList = new HashSet<>();
//        for (HistoricActivityInstance i: list) {
//            for(HistoricActivityInstance j : list){
//                if(i!=j){
//                    keyList.add(i.getActivityId()+j.getActivityId());
//                }
//            }
//        }
//        //高亮连线ID
//        Set<String> highLine = new HashSet<>();
//        keyList.forEach(s->highLine.add(map.get(s)));
//
//
//        //获取流程实例 历史节点（已完成）
//        List<HistoricActivityInstance> listFinished = historyService.createHistoricActivityInstanceQuery()
//                .processInstanceId(instanceId)
//                .finished()
//                .list();
//        //高亮节点ID
//        Set<String> highPoint = new HashSet<>();
//        listFinished.forEach(s->highPoint.add(s.getActivityId()));
//
//        //获取流程实例 历史节点（待办节点）
//        List<HistoricActivityInstance> listUnFinished = historyService.createHistoricActivityInstanceQuery()
//                .processInstanceId(instanceId)
//                .unfinished()
//                .list();
//
//        //需要移除的高亮连线
//        Set<String> set = new HashSet<>();
//        //待办高亮节点
//        Set<String> waitingToDo = new HashSet<>();
//        listUnFinished.forEach(s->{
//            waitingToDo.add(s.getActivityId());
//
//            for (FlowElement flowElement : flowElements) {
//                //判断是否是 用户节点
//                if (flowElement instanceof UserTask) {
//                    UserTask userTask = (UserTask) flowElement;
//
//                    if(userTask.getId().equals(s.getActivityId())){
//                        List<SequenceFlow> outgoingFlows = userTask.getOutgoingFlows();
//                        //因为 高亮连线查询的是所有节点  两两组合 把待办 之后  往外发出的连线 也包含进去了  所以要把高亮待办节点 之后 即出的连线去掉
//                        if(outgoingFlows!=null&& outgoingFlows.size()>0){
//                            outgoingFlows.forEach(a-> {
//                                if(a.getSourceRef().equals(s.getActivityId())){
//                                    set.add(a.getId());
//                                }
//                            });
//                        }
//                    }
//                }
//            }
//        });
//
//        highLine.removeAll(set);
//
//
//        Set<String> iDo = new HashSet<>(); //存放 高亮 我的办理节点
//        //当前用户已完成的任务
//        List<HistoricTaskInstance> taskInstanceList = historyService.createHistoricTaskInstanceQuery()
//                .taskAssignee("zhangsan")  //当前用户
//                .finished()
//                .processInstanceId(instanceId).list();
//
//        taskInstanceList.forEach(a->iDo.add(a.getTaskDefinitionKey()));
//
//        Map<String,Object> reMap = new HashMap<>();
//        reMap.put("highPoint",highPoint);
//        reMap.put("highLine",highLine);
//        reMap.put("waitingToDo",waitingToDo);
//        reMap.put("iDo",iDo);
//
//        return reMap;
//    }

//
//    private void setVariables(List<Map<String, Object>> listNew, List<Map<String, Object>> listOld) {
//        if (!CollectionUtils.isEmpty(listOld)) {
//            for (Map<String, Object> hipro : listOld) {
//                List<HistoricVariableInstance> variables = historyService.createHistoricVariableInstanceQuery().
//                        processInstanceId((String) hipro.get("PROC_INST_ID_")).list();
//                if (!CollectionUtils.isEmpty(variables)) {
//                    for (HistoricVariableInstance variable : variables) {
//                        hipro.put(variable.getVariableName(), variable.getValue());
//                    }
//                }
//                listNew.add(hipro);
//            }
//        }
//    }
}
